﻿/// <reference path="vswd-ext_2.2.js" />
/********************poi.js*********************************
*Create Date: 2012-5
*Description : this js file use ext js to create AJAX message function window 
*********************************************************************/
Ext.ns('OTA');
OTA.version = '1.0';
var g_OTAWindowObject;

function OTAWindow() {
    var pagesize = 2000;
    
    
    var trackertypefields = [{ name: "ModelIndex", type: "integer" },"ModelName",{name:"NotInUse",type:"integer"}];
    var trackertypestore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: "HandlerGetAllModel",
            method: "POST"
        }),
        reader: new Ext.data.JsonReader({
            fields: trackertypefields,
            root: ""
        })
    });

    var fields = [{name:"choosed",type:"boolean"},"sssid", "trackername", "modelname", { name: "modeltypeid", type: "integer" }, "firmware_ver", "firmware_to_ver","btnupload","btncancel", "last_upgrade_time",{name:"updating",type:"boolean"},{name:"updateprogress",type:"integer"},'mydisplay'];
    var _selectedrecord;

    var chooseboxota = new Ext.form.Checkbox({
        allowBlank: true,
        maxLength: 3
    });
    
    var checkColumnOTA = new Ext.grid.CheckColumn({
       header: '',
       width:25,
       sortable: false,
       dataIndex: 'choosed',
       editor: chooseboxota
    });

    
    var trackerstore = new Ext.data.GroupingStore({
        autoSave: true,
        proxy: new Ext.data.HttpProxy({
            url: "HandlerSearchOTADevice",
            method: "POST"
        }),
        reader: new Ext.data.JsonReader({
            fields: fields
        }),
        sortInfo:{field: 'modelname', direction: "ASC"},
        groupField:'modelname'
    });
    
//    trackerstore.addListener('load', function(sto, records, options) {
//        var i = 0;
//        for (i = 0; i < records.length; i++) {
//            var record = records[i];
//            if (record.get("updating")) 
//                record.set("btn", "icon-downloadmedia");
//            else
//                record.set("btn", "icon-getmedia");
//        }
//    });

    
    var trackNameCombo = getTrackerCheckboxCombo(true);
    
    var trackerTypeCombo = new Ext.form.ComboBox({
        store: trackertypestore,
        mode: 'local',
        displayField: 'ModelName',
        width: 100,
        valueField: 'ModelIndex',
        triggerAction: 'all',
        //forceSelection:true,
        disableKeyFilter:true,
        fieldLabel: _ImageButtonText_TrackerType,
        editable: true
    });
    
    trackerTypeCombo.on('keyup', function() {
        trackertypestore.filter('ModelName', trackerTypeCombo.getRawValue(), true, false);
        trackerTypeCombo.bindStore(trackertypestore);
    });

    trackerTypeCombo.on('blur', function() {
        trackertypestore.clearFilter();
        trackerTypeCombo.bindStore(trackertypestore);
    });
    
    trackerTypeCombo.on('select',function(obj,record,index){
        otastore.reload({
            params:{
                typeid:record.get('ModelIndex')
            }
        });
    }); 
    
    var otastore = new Ext.data.Store({
       proxy: new Ext.data.HttpProxy({
            url: "HandlerSearchOTAFiles",
            method: "POST"
        }),
        reader: new Ext.data.JsonReader({
            fields: ['filename']
        }),
        baseParams:{
            typeid:'-1'
        }
    });
    
    var otaFileCombo = new Ext.form.ComboBox({
        store: otastore,
        mode: 'local',
        displayField: 'filename',
        width: 200,
        valueField: 'filename',
        enableKeyEvents: true,
        triggerAction:'all',
        editable: false
    });
    
    otaFileCombo.on('select',function(obj,record,index){
        trackerstore.each(function(r){
            if(r.get('modeltypeid') == trackerTypeCombo.getValue() && r.get('firmware_ver').indexOf(firmwareeditor.getValue()) != -1){
                r.set('firmware_to_ver',record.get('filename'));
            }
        });
    });
    
    trackertypestore.load({params:{noneednouse:1}});
    
    var firmwareeditor = new Ext.form.TextField({
        width: 50,
        value: '',
        allowBlank :true,
        blankText : _Message_BlankText
    });
    var testi=0;
    var tbar = new Ext.Toolbar({
        items: [_TrackerMain_TrackerName + ':',
        trackNameCombo,
        _ImageButtonText_TrackerType + ':',
        trackerTypeCombo,
        {
            xtype: 'tbseparator', width: 5
        }
        , _TrackerMain_Firmware_Ver + ':'
        , firmwareeditor

        , {
            tooltip: { text: _TrackerMain_Search, autoHide: true },
            icon: 'images/search16.gif',
            handler: function() {
                trackerstore.reload({
                    timeout: 60000
                    , params: {
                        sssids: trackNameCombo.getValue(),
                        trackertypeids: trackerTypeCombo.getValue(),
                        trackerfirmware: firmwareeditor.getValue(),
                        start: 0,
                        limit: pagesize
                    }
                });
            }
        }
//        , {
//            tooltip: { text: "test", autoHide: true },
//            icon: 'images/search16.gif',
//            handler: function() {
//            setInterval(function() {
//                    testi++;
//                    trackerstore.each(function(record) {
//                    g_OTAWindowObject.changeUpgradeProgress(record.get('sssid'), 100, testi);
//                    });
//                }, 1000);
//            }
//        }
        , {
            xtype: 'tbseparator', width: 5
        }
         , _TrackerMain_ChangeUpgradeBatch + ":"
        , otaFileCombo
        ]
    });

    var grdviewgroup = new Ext.grid.GroupingView({
        startCollapsed: false,
        //forceFit:true,
        groupTextTpl: '{gvalue}'
    });
    
    Ext.util.Format.comboRenderer = function (combo) {
        return function (value, metaData, record, rowIndex, colIndex, store) {
            var record = combo.findRecord(combo.valueField, value);
            return record ? record.get(combo.displayField) : combo.valueNotFoundText;
        }
    };
   
    var allfilesstore =new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({
                url: "HandlerSearchOTAFiles",
                method: "POST"
            }),
            reader: new Ext.data.JsonReader({
                fields: ['filename']
            })
    });
    
    
    var combo =new Ext.form.ComboBox({
       store: allfilesstore,
       displayField:'filename',
       valueField: 'filename',
       triggerAction: 'all',
	   mode: 'local',
	   selectOnFocus: true,
	   typeAhead: true,
       disableKeyFilter : true,
       forceSelection:true,
       editable: false,
       lazyRender: true
       
       //listClass: 'x-combo-list-small'
    });
    
//    combo.on('blur',function(obj){
//        alert(combo.getValue());
//    });

    OTA.Grid = Ext.extend(Ext.grid.EditorGridPanel, {
        initComponent: function() {
            // Create RowActions Plugin
            this.action = new Ext.ux.grid.RowActions({
                width: 180
		        , keepSelection: false
		        , actions: [{
		            iconCls: 'icon-upgrade'
			            , tooltip: _CommandExpression_OTAUpgrade
		            }, {
		            iconCls: 'icon-cancelupgrade'
			            , tooltip: _CommandExpression_CancelOTA
                    }]

		        , callbacks: {
		            'icon-upgrade': function(grid, record, action, row, col) {
		                var sssid = record.get('sssid');
		                var mt88cmd = EnumMT88Command.OTA_CHECK;
		                var mt88param = record.get("firmware_to_ver") + "," + record.get("modeltypeid") + "," + record.get("firmware_ver");
		                var gvvtcommand = EnumGPRSCommand.NotSupportThisCommand;
		                var gvvtparam = "";
		                var gbcommand = "";
		                var gbparam = 0;
		                if (record.get("firmware_to_ver") != null) {
		                    if (record.get("firmware_to_ver").length == 0) {
		                        g_OTAWindowObject.changeUpgradeProgress(sssid, 100, 0);
		                        g_OTAWindowObject.changeDisplay(sssid, _Message_OTA_NoFile);
		                    }
		                    else {
		                        g_OTAWindowObject.changeUpgradeProgress(sssid, 100, 0);
		                        g_OTAWindowObject.changeDisplay(sssid, _TrackerMain_Sending);
		                        if (sssid != "")
		                            addOneTCPCommand(sssid, gvvtcommand, gvvtparam, mt88cmd, mt88param, gbcommand, gbparam);
		                    }
		                }
		            }

		            , 'icon-cancelupgrade': function(grid, record, action, row, col) {
		                var sssid = record.get('sssid');
		                var sssid = record.get('sssid');
		                var mt88cmd = EnumMT88Command.OTA_CANCEL;
		                var mt88param = "";
		                var gvvtcommand = EnumGPRSCommand.NotSupportThisCommand;
		                var gvvtparam = "";
		                var gbcommand = "";
		                var gbparam = 0;
		                g_OTAWindowObject.changeUpgradeProgress(sssid, 100, 0);
		                g_OTAWindowObject.changeDisplay(sssid, _TrackerMain_Sending);
		                if (sssid != "")
		                    addOneTCPCommand(sssid, gvvtcommand, gvvtparam, mt88cmd, mt88param, gbcommand, gbparam);
		            }
		        }
            });

            //            // dummy action event handler - just outputs some arguments to console
            //            this.action.on({
            //                action: function(grid, record, action, row, col) {
            //                    Ext.ux.Toast.msg('Event: action', 'You have clicked row: <b>{0}</b>, action: <b>{1}</b>', row, action);
            //                }
            //            });

            // configure the grid
            Ext.apply(this, {
                //colModel: colPhotoListColumnModel
                columns: [
                 checkColumnOTA
                 , {
                     header: _TrackerMain_TrackerName,
                     width: 180,
                     sortable: false,
                     menuDisabled: true,
                     dataIndex: 'sssid',
                     renderer: function(value) {
                         var count = trackNameCombo.getStore().getCount();
                         for (var i = 0; i < count; i++) {
                             var id = trackNameCombo.getStore().getAt(i).get('snid');
                             if (id == value) {
                                 return trackNameCombo.getStore().getAt(i).get('trackname');
                             }
                         }
                         return "";
                     }
                 }, {
                     header: _ImageButtonText_TrackerType,
                     width: 70,
                     sortable: false,
                     menuDisabled: true,
                     dataIndex: 'modelname'
                 }, {
                     header: _TrackerMain_Firmware_Ver,
                     width: 200,
                     sortable: false,
                     menuDisabled: true,
                     dataIndex: 'firmware_ver'
                 }, {
                     header: _TrackerMain_Upgrade_Ver,
                     sortable: false,
                     menuDisabled: true,
                     //id:'otafirmwareto',
                     dataIndex: 'firmware_to_ver',
                     width: 200,
                     disableKeyFilter: true,
                     forceSelection: true,
                     editor: combo
                     //renderer: Ext.util.Format.comboRenderer(combo)
                 }, new Ext.ux.ProgressColumn({
                     sortable: false,
                     menuDisabled: true,
                     header: _Photo_Uploaded,
                     width: 330,
                     dataIndex: 'updateprogress',
                     divisor: 'total',
                     align: 'center',
                     renderer: function(value, meta, record, rowIndex, colIndex, store, pct) {
                         if (record.get("mydisplay").toString().length > 0)
                             return record.get("mydisplay");
                         else
                             return Ext.util.Format.number(pct, "0.0%");
                     }
                 })
                 , this.action
            ]

	        , plugins: [this.action, checkColumnOTA]
		    , loadMask: true
        	, viewConfig: { forceFit: true }
        	, stripeRows: true
            , loadMask: true
        	, view: grdviewgroup

            });
            OTA.Grid.superclass.initComponent.apply(this, arguments);
        }
	    , onRender: function() {
	        OTA.Grid.superclass.onRender.apply(this, arguments);
	    }
    });

    var grid = new OTA.Grid({
        store: trackerstore,
        autoWidth: true,
        height: 300,
        clicksToEdit: 1,
        selModel:new Ext.grid.RowSelectionModel({singleSelect : true})
        
    });
    
    
    var timer = setInterval(function(){
        trackerstore.each(function(record){
            if(noresponsesssidArray.indexOf(record.get('sssid')) == -1)
                noresponsesssidArray.push(record.get('sssid'));
        });
    },15000);
    
//    grid.getSelectionModel().on('selectionchange',function(){
//        alert('aaa');
//    });
//    
//    combo.addListener('select',function(obj,rec,index){
//         if(grid.getSelectionModel().getCount()>0){
//            var record = grid.getSelectionModel().getSelected();
//            //alert(rec.get('firmware_var'));
//            //record.set('firmware_to_ver',rec.get('firmware_var'));
//         }
//    });

    var btnSelectAll = new Ext.Button({
        text: _Photo_SelectAll,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            trackerstore.each(function(record) {
                record.set("choosed", true);
            });
        }
    });

    var btnSelectNone = new Ext.Button({
        text: _Photo_SelectNone,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            trackerstore.each(function(record) {
                record.set("choosed", false);
            });
        }
    });

    var btnUpdateSelected = new Ext.Button({
        text: _TrackerMain_UpdateSelected,
        style: 'margin-right:16px',
        width: 80,
        handler: function() {
            var sssidarray = [];
            var commandarray = [];
            var paramarray = [];
            trackerstore.each(function(record) {
                if (record.get("choosed")) {
                    if (record.get("firmware_to_ver") != null) {
                        if (record.get("firmware_to_ver").length == 0) {
                            g_OTAWindowObject.changeUpgradeProgress(sssid, 100, 0);
                            g_OTAWindowObject.changeDisplay(sssid, _Message_OTA_NoFile);
                        }
                        else {
                            var sssid = record.get("sssid");
                            sssidarray.push(sssid);
                            commandarray.push(EnumMT88Command.OTA_CHECK);
                            paramarray.push(record.get("firmware_to_ver") + "," + record.get("modeltypeid") + "," + record.get("firmware_ver"));
                            g_OTAWindowObject.changeUpgradeProgress(sssid, 100, 0);
                            g_OTAWindowObject.changeDisplay(sssid, _TrackerMain_Sending);

                        }
                    }
                }
            });
            addTCPCommandWithDiffParamForMT(sssidarray, commandarray, paramarray);
        }
    });
    
    var btnReadSelectedFirmware = new Ext.Button({
        text:_TrackerMain_ReadCurrentFirmwareVer,
        style: 'margin-right:16px',
        handler: function() {
            var sssidarray = [];
            var commandarray = [];
            var paramarray = [];
            trackerstore.each(function(record) {
                if(record.get("choosed")){
                    var sssid = record.get("sssid");
                    sssidarray.push(sssid);
                    commandarray.push(EnumMT88Command.Read_Firmware_version_and_SN);
                    paramarray.push("");
                    g_OTAWindowObject.changeUpgradeProgress(sssid,100,0);
                    g_OTAWindowObject.changeDisplay(sssid,_TrackerMain_Sending);
                    
                   
                }
            });
            addTCPCommandWithDiffParamForMT(sssidarray,commandarray,paramarray);
        }
    });
    
    var btnCancelUpdate = new Ext.Button({
        text:_CommandExpression_CancelOTA,
        style: 'margin-right:16px',
        handler: function() {
            var sssidarray = [];
            var commandarray = [];
            var paramarray = [];
            trackerstore.each(function(record) {
                if(record.get("choosed")){
                    var sssid = record.get("sssid");
                     sssidarray.push(sssid);
                    commandarray.push(EnumMT88Command.OTA_CANCEL);
                    paramarray.push("");
                    g_OTAWindowObject.changeUpgradeProgress(sssid,100,0);
                    g_OTAWindowObject.changeDisplay(sssid,_TrackerMain_Sending);
                    
                   
                }
            });
            addTCPCommandWithDiffParamForMT(sssidarray,commandarray,paramarray);
        }
    });
    
    var win = new Ext.Window({
        title: _TrackerMain_OTA,
        layout: 'fit',
        height: 600,
        width: 1150,
        items: grid,
        tbar: tbar,
        constrain:true,
        
        minimizable: true,
         listeners: {
            'minimize': function() {
                addTaskButtonForWindow(win);
            }
        },
        buttons:[btnSelectAll,btnSelectNone,btnReadSelectedFirmware,btnUpdateSelected,btnCancelUpdate]
    });
    
    
    
    this.show = function() {
        if (!win.isVisible())
            win.show();
    };

    this.close = function() {
        if (win != null)
            win.close();
    };

    this.hide = function() {
        if (win != null) {
            win.hide();
            g_OTAWindowObject = null;
        }
    };



    this.changeUpgradeProgress = function(sssid, total, current) {
        var index = trackerstore.findBy(function(record, id) {
            return record.get("sssid") == sssid;
        });
        if (index != -1) {
            var record = trackerstore.getAt(index);
            record.set("total", total);
            record.set("updateprogress", current);
            if(current<total)
                record.set("mydisplay","");
            else
                record.set("mydisplay",_Message_OTA_Writing);
        }
//            if(imgname != _lastUploadImage){
//                this.completeUploadImg();
//                _lastUploadImage = imgname;
//            }
//            try{
//                trackerstore.each(function(record) {
//                    var tmpsssid = record.get("sssid");
//                    if (tmpsssid == sssid) {
//                        record.set("total", total);
//                        record.set("updateprogress", current);
//                        if(current<total)
//                            record.set("mydisplay","");
//                        else
//                            record.set("mydisplay",_Message_OTA_Writing);
//                    }
//                });
//            }
//            catch(err){
//            }
    };

    this.changeDisplay = function(sssid, mydisplay) {
        var index = trackerstore.findBy(function(record, id) {
            return record.get("sssid") == sssid;
        });
        if (index != -1) {
            var record = trackerstore.getAt(index);
            if(record.get("mydisplay") == _Message_OTA_Success){
                if(mydisplay == _TrackerMain_Sending)
                    record.set("mydisplay",mydisplay);
            }
            else if(mydisplay == _TrackerMain_TimeOut|| mydisplay == _TrackerMain_NotOnline){
                if(record.get("mydisplay") == _TrackerMain_Sending)
                    record.set("mydisplay",mydisplay);
            }
            else
                record.set("mydisplay",mydisplay);
        }
//        try{
//            trackerstore.each(function(record){
//                if(record.get("sssid") == sssid){
//                    if(record.get("mydisplay") == _Message_OTA_Success){
//                        if(mydisplay == _TrackerMain_Sending)
//                            record.set("mydisplay",mydisplay);
//                    }
//                    else if(mydisplay == _TrackerMain_TimeOut|| mydisplay == _TrackerMain_NotOnline){
//                        if(record.get("mydisplay") == _TrackerMain_Sending)
//                            record.set("mydisplay",mydisplay);
//                    }
//                    else
//                        record.set("mydisplay",mydisplay);
//                }
//            });
//        }catch(err){
//            }
    };

    this.changeOldFirmware = function(sssid, oldfirmware) {
        var index = trackerstore.findBy(function(record, id) {
            return record.get("sssid") == sssid;
        });
        if (index != -1) {
            var record = trackerstore.getAt(index);
            record.set("firmware_ver", oldfirmware);
        }
        //        try{
        //            trackerstore.each(function(record){
        //                if(record.get("sssid") == sssid){
        //                    record.set("firmware_ver",oldfirmware);
        //                }
        //            });
        //        }catch(err){
        //            }
    };
    
    /* to patch when upgrade finished not show success*/
    this.upgradePatch = function(sssid) {
        var index = trackerstore.findBy(function(record, id) {
            return (record.get("sssid") == sssid && record.get("updateprogress") == record.get("total") && record.get("updateprogress")>0);
        });
        if (index != -1) {
            var record = trackerstore.getAt(index);
            record.set("mydisplay", _Message_OTA_Success);
        }
        //        try{
        //            trackerstore.each(function(record){
        //                if(record.get("sssid") == sssid){
        //                     if( (record.get("updateprogress") == record.get("total")) && record.get("updateprogress")>0){
        //                         record.set("mydisplay",_Message_OTA_Success);
        //                     }
        //                }
        //            });
        //        }catch(err){
        //            }
    };
    
    this.completeUpgrade= function() {
        trackerstore.each(function(record) {
            var tmpsssid = record.get("sssid");
//            if (tmpsssid == _lastUploadImage) {
//                record.set("total", 10);
//                record.set("current", 10);
//            }
        });
    };
    
    trackerstore.on('beforeload', function(store) {
        trackerstore.baseParams = {
            sssids:trackNameCombo.getValue(),
            trackertypeids: trackerTypeCombo.getValue(),
            trackerfirmware:firmwareeditor.getValue()
        }
    });
   
    trackerstore.on('load' ,function(store,records){
        grid.getSelectionModel().on('rowselect',function(selModel){
            if(selModel.getCount()>0){
                var record = selModel.getSelected();
                allfilesstore.load({
                    params:{
                        typeid:record.get('modeltypeid'),
                        oldfirmware:record.get('firmware_ver')
                    }
                 });
            }
            
        });
        store.each(function(record){
            if(noresponsesssidArray.indexOf(record.get("sssid")) == -1)
                noresponsesssidArray.push(record.get("sssid"));
        });
        if (noresponsesssidArray.length > 0) {
            window.setTimeout("searchResponseWithStatus()", 3000);
        }
    });
   
    win.show();
    
    win.on('close',function(obj){
        g_OTAWindowObject = null;
        window.clearInterval(timer);
        timer = null;
        
    });
    
    trackerstore.load({
        params: {
            sssids:'',
            trackertypeids: '',
            trackerfirmware:'',
            start: 0,
            limit: pagesize
        }
    });
    
    g_OTAWindowObject = this;
}